<template>
  <view class="admin-feedback-container">
 

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 错误提示 -->
    <view v-else-if="error" class="error-container">
      <text class="error-text">{{ error }}</text>
      <view class="retry-btn" @click="fetchFeedbackDetail">
        <text class="retry-text">重试</text>
      </view>
    </view>

    <!-- 反馈详情 -->
    <view v-else-if="feedbackDetail" class="feedback-detail">
      <!-- 用户信息 -->
      <view class="user-info">
        <text class="username">{{ feedbackDetail.user.username }}</text>
        <text class="user-role">{{ feedbackDetail.user.role === 1 ? '管理员' : '普通用户' }}</text>
      </view>

      <!-- 反馈类型和状态 -->
      <view class="feedback-meta">
        <text class="feedback-type">{{ feedbackDetail.feedback_type.message }}</text>
        <text class="feedback-status" :class="`status-${feedbackDetail.status.code}`">{{ feedbackDetail.status.message }}</text>
      </view>

      <!-- 反馈内容 -->
      <view class="feedback-content">
        <text>{{ feedbackDetail.content }}</text>
      </view>

      <!-- 已有图片展示 -->
      <view v-if="feedbackDetail.images && feedbackDetail.images.length > 0" class="images-section">
        <text class="section-title">反馈图片</text>
        <view class="images-container">
          <view 
            v-for="(image, imgIndex) in feedbackDetail.images" 
            :key="imgIndex" 
            class="image-item"
            @click="previewImage(image.url)"
          >
            <u-image width="100%" height="100%" :src="SERVER_BASE_URL + image.url" mode="aspectFill">
              <template #loading>
                <u-loading></u-loading>
              </template>
              <template #error>
                <view style="font-size: 24rpx;">加载失败</view>
              </template>
            </u-image>
            <text class="image-type">{{ image.photo_type.message }}</text>
          </view>
        </view>
      </view>

      <!-- 处理人信息（如果已处理） -->
      <view v-if="feedbackDetail.handler && feedbackDetail.handler.username" class="handler-info">
        <text class="handler-label">处理人：</text>
        <text class="handler-name">{{ feedbackDetail.handler.username }}</text>
      </view>

      <!-- 处理结果（如果已处理） -->
      <view v-if="feedbackDetail.result" class="result-info">
        <text class="result-label">处理结果：</text>
        <text class="result-content">{{ feedbackDetail.result }}</text>
      </view>

      <!-- 处理反馈表单 -->
      <view v-if="!feedbackDetail.result || feedbackDetail.status.code === 1" class="handle-form">
        <text class="section-title">处理反馈</text>
        
        <!-- 上传处理图片 -->
        <view class="form-item">
          <text class="form-label">上传处理图片（最多9张）</text>
          <view class="image-upload-section">
            <!-- 图片选择按钮 -->
            <view class="add-image-btn" @click="chooseImage" :class="{ disabled: images.length >= 9 || uploading }">
              <view class="add-icon">+</view>
              <text class="add-text">{{ images.length }}/9</text>
            </view>
            
            <!-- 图片预览区域 -->
            <view v-for="(image, index) in images" :key="index" class="image-preview-item" @click="previewUploadingImage(index)">
              <u-image width="100%" height="100%" :src="image.url" mode="aspectFill"></u-image>
              <view class="delete-btn" @click.stop="deleteImage(index)">
                <text class="delete-icon">×</text>
              </view>
              
              <!-- 上传中状态 -->
              <view v-if="image.status === 'uploading'" class="uploading-overlay">
                <view class="loading-spinner"></view>
              </view>
              
              <!-- 上传失败状态 -->
              <view v-if="image.status === 'error'" class="image-status-indicator">
                上传失败
              </view>
              
              <!-- 上传成功状态 -->
              <view v-if="image.status === 'success'" class="image-status-indicator">
                上传成功
              </view>
            </view>
          </view>
          <text class="upload-tip">支持JPG、PNG等格式，单张不超过5MB</text>
          
          <!-- 上传进度条 -->
          <view v-if="uploading" class="progress-container">
            <view class="progress-bar">
              <view class="progress-fill" :style="{ width: uploadProgress + '%' }"></view>
            </view>
            <text class="progress-text">{{ uploadProgress }}%</text>
          </view>
        </view>

        <!-- 处理结果输入 -->
        <view class="form-item">
          <text class="form-label">处理结果 *</text>
          <textarea 
            class="result-input"
            v-model="handleForm.result"
            placeholder="请输入处理结果"
            placeholder-class="placeholder-text"
            maxlength="500"
          ></textarea>
          <text class="char-count">{{ handleForm.result.length }}/500</text>
          <text v-if="formErrors.result" class="error-text">{{ formErrors.result }}</text>
        </view>

        <!-- 提交按钮 -->
        <view style="text-align: right;">
          <u-button size="medium" :loading="submitting || uploading" class="submit-btn" @click="handleFeedback" :disabled="submitting || uploading">提交处理</u-button>
        </view>
      </view>

      <!-- 时间信息 -->
      <view class="time-info">
        <text class="create-time">提交时间：{{ feedbackDetail.create_time }}</text>
        <text v-if="feedbackDetail.update_time" class="update-time">更新时间：{{ feedbackDetail.update_time }}</text>
      </view>
    </view>

    <!-- 提示消息 -->
    <view v-if="showMessage" class="toast" :class="messageType">
      <text class="toast-text">{{ messageContent }}</text>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { get_feedback_list, handle_feedback, SERVER_BASE_URL } from '@/static/apis/wzry';
import { onLoad } from '@dcloudio/uni-app';
// 状态管理
const loading = ref(false);
const error = ref('');
const feedbackDetail = ref(null);
const feedbackId = ref('');

// 表单状态
const submitting = ref(false);
const formErrors = ref({});

// 图片上传相关状态
const images = ref([]);
const uploading = ref(false);
const uploadProgress = ref(0);
const supportedFormats = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
const currentFeedbackId = ref('');

// 提示消息
const showMessage = ref(false);
const messageType = ref('success');
const messageContent = ref('');

// 处理表单
const handleForm = reactive({
  result: ''
});

onLoad(async (options) => {
  feedbackId.value = options.feedback_id;
  console.log(feedbackId.value);
});



// 显示提示消息
const showToast = (type, content) => {
  messageType.value = type;
  messageContent.value = content;
  showMessage.value = true;
  setTimeout(() => {
    showMessage.value = false;
  }, 2000);
};

// 获取反馈详情
const fetchFeedbackDetail = async () => {
  
  if (!feedbackId.value) {
    error.value = '缺少反馈ID';
    return;
  }
  
  loading.value = true;
  error.value = '';
  
  try {
    const response = await get_feedback_list({ feedback_id: feedbackId.value });
    if (response.code === 0 && response.data && response.data.length > 0) {
      feedbackDetail.value = response.data[0];
    } else {
      error.value = response.message || '获取反馈详情失败';
    }
  } catch (err) {
    error.value = err.message || '网络异常，请稍后重试';
  } finally {
    loading.value = false;
  }
};

// 验证表单
const validateForm = () => {
  formErrors.value = {};
  let isValid = true;
  
  if (!handleForm.result || handleForm.result.trim() === '') {
    formErrors.value.result = '请输入处理结果';
    isValid = false;
  } else if (handleForm.result.trim().length < 2) {
    formErrors.value.result = '处理结果至少需要2个字符';
    isValid = false;
  }
  
  return isValid;
};

// 处理反馈
const handleFeedback = async () => {
  if (!validateForm()) {
    return;
  }
  
  try {
    submitting.value = true;
    
    // 先上传图片（如果有）
    if (images.value.length > 0) {
      currentFeedbackId.value = feedbackId.value;
      uploading.value = true;
      await uploadImagesSequentially(feedbackId.value);
    }
    
    // 提交处理结果
    const response = await handle_feedback({
      feedback_id: feedbackId.value,
      result: handleForm.result
    });
    
    if (response.code === 0) {
      showToast('success', '处理成功');
      setTimeout(() => {
        goBack();
      }, 1500);
    } else {
      showToast('error', response.message || '处理失败，请稍后重试');
    }
  } catch (error) {
    console.error('处理反馈失败:', error);
    showToast('error', '网络错误，请稍后重试');
  } finally {
    submitting.value = false;
    uploading.value = false;
  }
};

// 封装uni.uploadFile为Promise
const uploadImageFile = (options) => {
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      ...options,
      success: (res) => {
        resolve(res);
      },
      fail: (error) => {
        reject(error);
      }
    });
  });
};

// 带重试机制的图片上传
const uploadWithRetry = async (image, feedbackId, index) => {
  const MAX_RETRIES = 3;
  let lastError = null;
  
  for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
    if (attempt > 0) {
      image.retryCount++;
      showToast('warning', `正在重试上传图片 ${index + 1}（${attempt}/${MAX_RETRIES}）...`);
      
      // 指数退避策略
      const delay = Math.pow(2, attempt - 1) * 1000;
      await new Promise(resolve => setTimeout(resolve, delay));
    }
    
    try {
      image.status = 'uploading';
      
      // 管理员上传的图片类型固定为2
      const uploadResult = await uploadImageFile({
        url: SERVER_BASE_URL + 'api/feedback/upload_feedback_image/',
        filePath: image.url,
        name: 'image',
        formData: {
          feedback_id: feedbackId,
          photo_type: '2' // 管理员上传的图片类型固定为2
        }
      });
      
      const uploadResponse = JSON.parse(uploadResult.data);
      
      if (uploadResponse.code === 0) {
        image.status = 'success';
        return true;
      } else {
        image.status = 'error';
        image.errorMsg = uploadResponse.msg || '服务器错误';
        showToast('error', `图片 ${index + 1} 上传失败: ${image.errorMsg}`);
        return false;
      }
    } catch (error) {
      lastError = error;
      console.error(`上传图片失败 (${index + 1}/尝试${attempt + 1}):`, error);
    }
  }
  
  image.status = 'error';
  image.errorMsg = lastError ? lastError.errMsg || '网络异常' : '未知错误';
  showToast('error', `图片 ${index + 1} 上传失败（已重试${MAX_RETRIES}次）`);
  return false;
};

// 循环上传图片
const uploadImagesSequentially = async (feedbackId) => {
  const totalImages = images.value.length;
  let uploadedCount = 0;
  
  for (let i = 0; i < totalImages; i++) {
    const image = images.value[i];
    
    if (image.status !== 'success') {
      if (!image.retryCount) {
        image.retryCount = 0;
      }
      
      const success = await uploadWithRetry(image, feedbackId, i);
      if (success) {
        uploadedCount++;
        uploadProgress.value = Math.floor((uploadedCount / totalImages) * 100);
      }
    } else {
      uploadedCount++;
    }
  }
  
  const failedImages = images.value.filter(img => img.status === 'error');
  if (failedImages.length > 0) {
    showToast('error', `部分图片上传失败，共成功上传 ${uploadedCount}/${totalImages} 张`);
  }
};

	// 选择图片
	const chooseImage = async () => {
		// 计算还可以选择的图片数量
		const remainingCount = 9 - images.value.length;

		if (remainingCount <= 0) {
			showToast('error', '最多只能上传9张图片');
			return;
		}

		try {
			const res = await uni.chooseImage({
				count: remainingCount,
				sourceType: ['album', 'camera'] // 支持从相册和相机选择
			});

			// 处理选择的图片
			for (const tempFile of res.tempFiles) {
				// 检查文件大小（5MB限制）
				if (tempFile.size > 5 * 1024 * 1024) {
					showToast('error', `图片${tempFile.name}超过5MB限制`);
					continue;
				}

				// 检查文件格式，添加对tempFile.name是否存在的检查
				let fileExtension = '';
				if (tempFile.name) {
					fileExtension = tempFile.name.split('.').pop()?.toLowerCase() || '';
				} else if (tempFile.path) {
					// 如果name不存在，尝试从path中获取扩展名
					fileExtension = tempFile.path.split('.').pop()?.toLowerCase() || '';
				}
				
				// 如果无法获取扩展名或不支持的格式，跳过验证或默认允许
				if (fileExtension && !supportedFormats.includes(fileExtension)) {
					showToast('error', `不支持的图片格式: ${fileExtension}`);
					continue;
				}

				// 添加到图片列表
				images.value.push({
					url: tempFile.path,
					name: tempFile.name,
					size: tempFile.size,
					status: 'pending' // pending, uploading, success, error
				});
			}
		} catch (error) {
			if (error.errMsg !== 'chooseImage:fail cancel') {
				console.error('选择图片失败:', error);
				showToast('error', '选择图片失败，请重试');
			}
		}
	};
// 删除图片
const deleteImage = (index) => {
  images.value.splice(index, 1);
};

// 预览已上传图片
const previewImage = (url) => {
  uni.previewImage({
    urls: [SERVER_BASE_URL + url]
  });
};

// 预览正在上传的图片
const previewUploadingImage = (index) => {
  const urls = images.value.map(img => img.url);
  uni.previewImage({
    urls: urls,
    current: index
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 页面加载时获取详情
onMounted(() => {
  fetchFeedbackDetail();
});
</script>

<style scoped>
.admin-feedback-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}



.loading-container,
.error-container,
.empty-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 100rpx 0;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #07c160;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text,
.error-text,
.empty-text {
  font-size: 28rpx;
  color: #666;
  margin-top: 20rpx;
}

.retry-btn {
  margin-top: 20rpx;
  padding: 10rpx 40rpx;
  background-color: #07c160;
  color: #fff;
  border-radius: 20rpx;
}

.feedback-detail {
  background-color: #fff;
  border-radius: 20rpx;
  padding: 30rpx;
}

.user-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.username {
  font-size: 32rpx;
  font-weight: bold;
}

.user-role {
  font-size: 28rpx;
  color: #666;
}

.feedback-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.feedback-type {
  font-size: 28rpx;
  color: #333;
}

.feedback-status {
  font-size: 28rpx;
  padding: 4rpx 16rpx;
  border-radius: 16rpx;
}

.status-1 {
  background-color: #ff9800;
  color: #fff;
}

.status-2 {
  background-color: #4caf50;
  color: #fff;
}

.feedback-content {
  font-size: 30rpx;
  line-height: 1.5;
  color: #333;
  margin-bottom: 30rpx;
  padding: 20rpx;
  background-color: #f9f9f9;
  border-radius: 10rpx;
}

.images-section {
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 30rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  color: #333;
}

.images-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.image-item {
    width: 200rpx;
    height: 200rpx;
    position: relative;
    border-radius: 12rpx;
    overflow: hidden;
  }

.image-type {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  font-size: 20rpx;
  text-align: center;
  padding: 5rpx 0;
}

.handler-info,
.result-info {
  margin-bottom: 20rpx;
}

.handler-label,
.result-label {
  font-size: 28rpx;
  color: #666;
}

.handler-name {
  font-size: 28rpx;
  color: #333;
}

.result-content {
  font-size: 28rpx;
  color: #333;
  display: block;
  margin-top: 10rpx;
  line-height: 1.5;
}

.handle-form {
  margin-top: 40rpx;
  padding-top: 30rpx;
  border-top: 2rpx solid #eee;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #333;
  display: block;
  margin-bottom: 15rpx;
}

.image-upload-section {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.add-image-btn {
    width: 200rpx;
    height: 200rpx;
    border: 2rpx dashed #d9d9d9;
    border-radius: 12rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    background-color: #fafafa;
  }

.add-image-btn.disabled {
  opacity: 0.5;
}

.add-icon {
    font-size: 64rpx;
    color: #bfbfbf;
    margin-bottom: 8rpx;
  }

  .add-text {
    font-size: 24rpx;
    color: #999999;
  }

.image-preview-item {
    width: 200rpx;
    height: 200rpx;
    position: relative;
    border-radius: 12rpx;
    overflow: hidden;
    background-color: #f5f5f5;
    transition: all 0.3s ease;
    border: 1rpx solid #e0e0e0;
  }
  
  .image-preview-item:active {
    transform: scale(0.95);
  }

.delete-btn {
    position: absolute;
    top: -10rpx;
    right: -10rpx;
    width: 48rpx;
    height: 48rpx;
    background-color: rgba(0, 0, 0, 0.6);
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: background-color 0.3s ease;
  }

  .delete-btn:active {
    background-color: rgba(0, 0, 0, 0.8);
  }

  .delete-icon {
    color: #fff;
    font-size: 32rpx;
    line-height: 1;
  }

.uploading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.image-status-indicator {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  font-size: 24rpx;
  text-align: center;
  padding: 10rpx 0;
}

.upload-tip {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
  display: block;
}

.progress-container {
  margin-top: 20rpx;
  display: flex;
  align-items: center;
}

.progress-bar {
  flex: 1;
  height: 10rpx;
  background-color: #eee;
  border-radius: 5rpx;
  overflow: hidden;
  margin-right: 20rpx;
}

.progress-fill {
  height: 100%;
  background-color: #07c160;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 24rpx;
  color: #666;
}

.result-input {
  width: 100%;
  min-height: 200rpx;
  padding: 20rpx;
  border: 2rpx solid #ddd;
  border-radius: 10rpx;
  font-size: 28rpx;
  color: #333;
  background-color: #fff;
  box-sizing: border-box;
}

.char-count {
  font-size: 24rpx;
  color: #999;
  float: right;
  margin-top: 10rpx;
}

.error-text {
  font-size: 24rpx;
  color: #ff4d4f;
  margin-top: 10rpx;
  display: block;
}

.submit-btn {
    background-color: #1CC46D !important;
    color: #fff !important;
    font-size: 28rpx;
    padding: 20rpx 60rpx;
    transition: all 0.3s ease;
  }

  .submit-btn:disabled {
    background-color: #ccc !important;
  }
  
  .submit-btn:active:not(:disabled) {
    background-color: #0fa65a !important;
    transform: scale(0.98);
  }

.time-info {
  margin-top: 30rpx;
  padding-top: 20rpx;
  border-top: 2rpx solid #eee;
}

.create-time,
.update-time {
  font-size: 24rpx;
  color: #999;
  display: block;
  margin-bottom: 10rpx;
}

.toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 20rpx 40rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  z-index: 9999;
}

.toast.success {
  background-color: rgba(0, 0, 0, 0.7);
  color: #fff;
}

.toast.error,
.toast.warning {
  background-color: rgba(0, 0, 0, 0.7);
  color: #fff;
}
</style>